package com.crm.controller;

import com.crm.base.BaseController;
import com.crm.base.ResultInfo;
import com.crm.query.SaleChanceQuery;
import com.crm.service.SaleChanceService;
import com.crm.service.UserService;
import com.crm.utils.CookieUtil;
import com.crm.utils.LoginUserUtil;
import com.crm.vo.SaleChance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("sale_chance")
public class SaleChanceController extends BaseController {

    @Autowired
    private SaleChanceService saleChanceService;

    @Autowired
    private UserService userService;

    @RequestMapping("index")
    public String index(){
        return "saleChance/sale_chance";
    }

    @GetMapping("list")
    @ResponseBody
    public Map<String,Object> querySaleChancesByParams(Integer flag,HttpServletRequest request,SaleChanceQuery saleChanceQuery){
        if(null!=flag&&flag==1){
            saleChanceQuery.setAssignMan(LoginUserUtil.releaseUserIdFromCookie(request));
        }
        return saleChanceService.querySaleChanceByParams(saleChanceQuery);
    }


    @RequestMapping("save")
    @ResponseBody
    public ResultInfo saveSaleChance(HttpServletRequest request, SaleChance saleChance){
        saleChance.setCreateMan(userService.selectByPrimaryKey(LoginUserUtil.releaseUserIdFromCookie(request)).getTrueName());
//        saleChanceService.saveSaleChance(saleChance);
//        return success("数据添加成功！");
        // 从cookie中获取用户姓名
        String userName = CookieUtil.getCookieValue(request, "userName");
        // 设置营销机会的创建人
        saleChance.setCreateMan(userName);
        // 添加营销机会的数据
        saleChanceService.saveSaleChance(saleChance);
        return success("营销机会数据添加成功！");
    }


    @RequestMapping("addOrUpdateSaleChancePage")
    public String addSaleChancePage(Integer id, Model model){
        if(null!=id){
            model.addAttribute("saleChance",saleChanceService.selectByPrimaryKey(id));
        }
        return "saleChance/add_update";
    }


    @RequestMapping("update")
    @ResponseBody
    public ResultInfo updateSaleChance(SaleChance saleChance){
        saleChanceService.updateSaleChances(saleChance);
        return success("机会数据更新成功！");
    }


    @RequestMapping("/delete")
    @ResponseBody
    public ResultInfo deleteSaleChance(Integer[] ids){
        saleChanceService.deleteSaleChance(ids);
        return success("机会数据删除成功！");
    }
}
